<?php
/**
 * User: dimka3210
 * Date: 19.11.13
 * Time: 20:33
 */

class MysqlStorage implements IStorage
{
    private $pdo;

    public function __construct($host, $user, $pass)
    {
        $this->pdo = new PDO($host, $user, $pass);
    }

    /**
     * @param int $limit
     * @param int $offset
     * @param bool $only_active
     * @return array
     */
    public function getRows($limit = 100, $offset = 0, $only_active = true)
    {
        $where = $only_active ? 'WHERE is_active = 1' : '';
        $sql = 'SELECT id, title, text, create_date, modify_date FROM news ' . $where . ' ORDER BY id DESC LIMIT :limit OFFSET :offset';
        $stmt = $this->pdo->prepare($sql);
        $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
        $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }

/*    public function addRow($data)
    {
        if (empty($data['title']) || empty($data['text'])) {
            throw new Exception('Не переданы обязательные поля');
        }
        $sql = 'INSERT INTO news (title, text, create_date, modify_date, is_active) VALUES (:title, :text, NOW(), NOW(), :on)';
        $stmt = $this->pdo->prepare($sql);
        $stmt->bindValue(':title', $data['title'], PDO::PARAM_STR);
        $stmt->bindValue(':text', $data['text'], PDO::PARAM_STR);
        $stmt->bindValue(':on', $data['active'], PDO::PARAM_INT);
        return $stmt->execute();
    }*/

    public function findRowById($id)
    {
        $stmt = $this->pdo->prepare('SELECT * FROM news WHERE id = ?');
        $stmt->bindValue(1, $id, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetch();
    }

    public function saveRow($data)
    {
        if (!isset($data['is_active'])) {
            $data['is_active'] = 0;
        }

        if (isset($data['id'])) {
            $sql = 'UPDATE news SET title=:title, text=:text, is_active=:active, modify_date=NOW() WHERE id = :id';
        } else {
            $sql = 'INSERT INTO news (title, text, is_active, create_date, modify_date) VALUES (:title, :text, :active, NOW(), NOW())';
        }

        $stmt = $this->pdo->prepare($sql);
        $stmt->bindParam(':title', $data['title'], PDO::PARAM_STR);
        $stmt->bindParam(':text', $data['text'], PDO::PARAM_STR);
        $stmt->bindParam(':active', $data['is_active'], PDO::PARAM_INT);
        if (isset($data['id'])) {
            $stmt->bindParam(':id', $data['id'], PDO::PARAM_INT);
        }
        $stmt->execute();
        return $this->pdo->lastInsertId();
    }

    public function deleteRow($id)
    {
        $sql = 'DELETE FROM news WHERE id = ?';
        $stmt = $this->pdo->prepare($sql);
        $stmt->bindParam(1, $id);
        return $stmt->execute();
    }
}